/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       LengYin Ltd.
 */

package com.platform.gateway.common.filter;

import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * @projectName:  platform-gateway-demo
 * @package:      com.platform.gateway.common.filters
 * @className:    LogsFilter.java
 * @description:  后置日志记录
 * @author:       OprCalf
 * @date:         2020年3月4日
 */
@Slf4j
@Component
public class LogsPostFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 要打印返回信息，必须得用"post"
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE + 6;
    }

    @Override
    public boolean shouldFilter() {
        final RequestContext ctx = RequestContext.getCurrentContext();
        // 当发生异常的时候,不是进行取值
        if (ctx.getThrowable() != null) {
            log.error("{}", ctx.getThrowable().fillInStackTrace());
            if (ctx.sendZuulResponse()) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    public Object run() {
        try {
            // 获取当前请求的对象
            final RequestContext ctx = RequestContext.getCurrentContext();
            // 打印返回的response信息
            final InputStream out = ctx.getResponseDataStream();
            // 获取返回的body里面的值
            final String outBody = StreamUtils.copyToString(out, Charset.forName("UTF-8"));
            // 当进入了限流的时候,此时返回的body里面的值为空,
            log.info("返回值：{}", outBody);
            // 把返回的body的值重新设置回去,前台才能拿到
            ctx.setResponseBody(outBody);

        }
        catch (final Exception e) {
            log.error("LogsFilter发生异常:{}", e);
        }
        return null;
    }
}